package com.gitee.wsl.ext.map.builder

import com.gitee.wsl.collections.bean.SampleMapEntry


interface MapBuilder<K, in V> {
    fun put(key: K, value: V)
    fun putAll(map: Map<K, V>)
}


inline fun <K, V> buildMap(builder: (MapBuilder<K, V>).() -> Unit): Map<K, V> {
    val result = HashMap<K, V>()
    object : MapBuilder<K, V> {
        override fun put(key: K, value: V) {
            result[key] = value
        }

        override fun putAll(map: Map<K, V>) {
            result.putAll(map)
        }
    }.builder()

    return result.replaceTrivialMap()
}


fun <K, V> Map<K, V>.replaceTrivialMap(): Map<K, V> = when (size) {
    0 -> emptyMap()
    1 -> {
        val entry = entries.single()
        SingletonMap(entry.key, entry.value)
    }

    else -> this
}

class SingletonMap<K, V>(val k: K, val v: V, ): AbstractMap<K,V>(){
    override val entries: Set<Map.Entry<K, V>> = setOf(SampleMapEntry(k,v))
}